//
//  Toolobject.m
//  YinDaOA
//
//  Created by Yinda on 15/1/12.
//  Copyright (c) 2015年 Zhang Yabei. All rights reserved.
//

#import "Toolobject.h"
#import "MBProgressHUD.h"
#import "Reachability.h"

@implementation Toolobject

+(NSInteger)returnthenetwork
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            return 0;
            break;
        case ReachableViaWWAN:
            return 1;
            break;
        case ReachableViaWiFi:
            return 2;
            break;
        default:
            return -1;
    }
}


// 删除字符串中的空格
+(NSString *)deleteSpacebar:(NSString *)str
{
    NSString *re = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    return re;
}

+(void)showAlterwithMessage:(NSString *)str
{
    UIAlertView *alet = [[UIAlertView alloc]initWithTitle:[UtilCheck language:@"title.title"] message:str delegate:nil cancelButtonTitle:[UtilCheck language:@"button.done"] otherButtonTitles:nil];
    [alet show];
}

+(void)showAlterwithMessage:(NSString *)str inVC:(UIViewController *)vc
{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"" message:str preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:[UtilCheck language:@"HUD.gotit"] style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertC addAction:action];
    [vc presentViewController:alertC animated:YES completion:nil];
    
}

+(void) showTextWithMessage:(NSString*) str {
    MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.label.text=str;
    [hud hideAnimated:YES afterDelay:1];
 
}


//邮箱格式检测
+ (BOOL)validateEmail: (NSString *) candidate
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:candidate];
}

+(BOOL)validateNumber:(NSString *)str
{
    NSScanner* scan = [NSScanner scannerWithString:str];
    int val;
    return  [scan scanInt:&val] && [scan isAtEnd];
}

+(BOOL)str:(NSString *)str1 ishas:(NSString *)str2
{
    NSRange range = [str1 rangeOfString:str2];
    if (range.location == NSNotFound)
    {
        return NO;
    }
    else
    {
        return YES;
    }
    
}
+(BOOL)isPureNumber:(NSString*)string{

    if (![self isfloat:string]&&![self validateNumber:string]) {
        return NO;
    }else{
        return YES;
    }
}

+ (BOOL)isfloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float flo;
    return([scan scanFloat:&flo]) && [scan isAtEnd];
}

+(NSString *)GetString:(NSDictionary *)dic forkey:(NSString *)key
{
    return [NSString stringWithFormat:@"%@",[dic objectForKey:key]];
}
//强转字符串类型
+(NSString *)stringwithfoarmat:(id)object{
    
    NSString *str=[NSString stringWithFormat:@"%@",object];
    return str;
}

+(NSString *)intervalFromLastDate: (NSString *) dateString1 toTheDate:(NSString *) dateString2
{
    NSLog(@"时间1 -%@           时间2--%@",dateString1,dateString2);
    NSArray *timeArray1=[dateString1 componentsSeparatedByString:@"."];
    dateString1=[timeArray1 objectAtIndex:0];
    
    
    NSArray *timeArray2=[dateString2 componentsSeparatedByString:@"."];
    dateString2=[timeArray2 objectAtIndex:0];
    
    NSLog(@"%@.....%@",dateString1,dateString2);
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    
    NSDate *d1=[date dateFromString:dateString1];
    
    NSTimeInterval late1=[d1 timeIntervalSince1970]*1;

    NSDate *d2=[date dateFromString:dateString2];
    
    NSTimeInterval late2=[d2 timeIntervalSince1970]*1;
    
    NSTimeInterval cha=late2-late1;
    NSString *timeString = @"";
    NSString *hour = @"";
    NSString *minute = @"";
    NSString *second = @"";
    
    second = [NSString stringWithFormat:@"%d", (int)cha%60];
    // min = [min substringToIndex:min.length-7];
    // 秒
    second =[NSString stringWithFormat:@"%@", second];
    
    
    
    minute = [NSString stringWithFormat:@"%d", (int)cha/60%60];
    // min = [min substringToIndex:min.length-7];
    // 分
    minute = [NSString stringWithFormat:@"%@", minute];
    
    // 小时
    hour = [NSString stringWithFormat:@"%d", (int)cha/3600];
    // house = [house substringToIndex:house.length-7];
    hour =[NSString stringWithFormat:@"%@", hour];
    
    timeString=[NSString stringWithFormat:@"%@:%@:%@",hour,minute,second];
    
    NSLog(@"两时间间隔为:%@",timeString);
    
    return timeString;
}

+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
    
}

+ (BOOL)isCameraAvailable {
    
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}


+ (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


//判断字符串是否为空
+(Boolean) IsEmptyString:(NSString*) string {
    
    if (!string) {
        return YES;
    } else if ([string isEqualToString:@""]) {
        return YES;
    } else if ([string isEqualToString:@"(null)"]) {
        return YES;
    } else if ([string isEqualToString:@"\"null\""]) {
        return YES;
    } else if ([string isEqualToString:@"null"]) {
        return YES;
    }
    else {
        return NO;
    }
}



+ (NSString *)DateString:(NSString *)inputDateStr FromDateFormatter:(NSString *)inputDateFormatter ToDateFormatter:(NSString *)outputDateFormatter {
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:inputDateFormatter];
    
    NSDate *theDate = [inputFormatter dateFromString:inputDateStr];
    
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:outputDateFormatter];
    NSString *outputDateStr = [outputFormatter stringFromDate:theDate];
    
    return outputDateStr;
}

+ (NSString *)stringFromDate:(NSDate *)date WithFormatter:(NSString *)dateFormatter {
    NSString *dateString;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dateFormatter];
    if (dateFormatter.length == 0) {
        [formatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    }
    dateString = [formatter stringFromDate:date];
    return dateString;
}


+ (BOOL) isMobile:(NSString *)mobileNumbel{
    
    
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,181(增加)
     */
    NSString * MOBIL = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,181(增加)
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBIL];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNumbel]
         || [regextestcm evaluateWithObject:mobileNumbel]
         || [regextestct evaluateWithObject:mobileNumbel]
         || [regextestcu evaluateWithObject:mobileNumbel])) {
        return YES;
    }
    
    return NO;
}

//16进制获取颜色
+(UIColor *) getColorByHexString: (NSString *) stringToConvert  alpha:(CGFloat)alpha{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6)
        return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor blackColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f)                         alpha:alpha];
}
//通过rgb获取颜色
+ (UIColor*)getColorByRGB:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha{
    return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha] ;
}


//是否是AppStore测试账号
+(BOOL)isAppStoreTestAccount {
    
    NSDictionary *accountdict = [THMangerTool getKeepAccout];
    if ([accountdict[@"username"] isEqualToString:APPSTOREACCOUNT]) {
        //应用商店测试账号
        return YES;
    }else{
        return NO;
    }

}


/**
 计算字符串高度
 
 @param string 字符串
 @param fontSize 字符size
 @return 字符串高度
 */
+ (CGFloat)heightForString:(NSString *)string width:(CGFloat)width fontSize:(CGFloat)fontSize {
    
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:CustomFont(fontSize)} context:nil];
    return rect.size.height;
}

/**
 计算字符串长度
 
 @param string 字符串
 @param fontSize 字符size
 @return 字符串长度
 */
+ (CGFloat)widthForString:(NSString *)string height:(CGFloat)height fontSize:(CGFloat)fontSize {
    
    NSDictionary *attributeDic = @{NSFontAttributeName:[UIFont systemFontOfSize: fontSize],NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, fontSize * 2) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:attributeDic context:nil];
    return rect.size.width;
    
}

@end


